package com.tiancheng.onecode.controller.admin.merchant;

import com.tiancheng.onecode.exception.Asserts;
import com.tiancheng.onecode.model.dto.PayMerchantDTO;
import com.tiancheng.onecode.model.request.admin.QueryBillReq;
import com.tiancheng.onecode.model.response.PageInfo;
import com.tiancheng.onecode.model.response.Result;
import com.tiancheng.onecode.model.response.admin.BillQueryExportRes;
import com.tiancheng.onecode.model.response.admin.BillQueryRes;
import com.tiancheng.onecode.model.response.admin.TradeStatisticsRes;
import com.tiancheng.onecode.service.IBillService;
import com.tiancheng.onecode.trade.enums.SettleStatusEnum;
import com.tiancheng.onecode.utils.AmountUtil;
import com.tiancheng.onecode.utils.DateTimeUtil;
import com.tiancheng.onecode.utils.ExcelUtil;
import com.tiancheng.onecode.utils.MerchantContext;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: kellen
 * @Description: 账单管理Controller 平台端
 * @Date: create in 2024/12/26 20:21
 */
@Slf4j
@RestController
@RequestMapping("/admin/merchant/bill")
public class MerchantBillAdminController {

    @Resource
    private IBillService billService;

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ResponseBody
    public Result<PageInfo<BillQueryRes>> queryPage(@RequestBody QueryBillReq params) {
        final PayMerchantDTO merchant = MerchantContext.getMerchant();
        if(null!=merchant && null==params.getPlatformMerchantId()){
            params.setPlatformMerchantId(merchant.getPlatformMerchantId());
        }
        PageInfo<BillQueryRes> pageInfo = billService.queryPage(params);
        return Result.success(pageInfo);
    }

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public void export(@RequestBody QueryBillReq params, HttpServletRequest request, HttpServletResponse response) throws IOException {
        final PayMerchantDTO merchant = MerchantContext.getMerchant();
        if(null!=merchant && null==params.getPlatformMerchantId()){
            params.setPlatformMerchantId(merchant.getPlatformMerchantId());
        }
        // 设置最多导出50000条
        params.setCurrentPage(1);
        params.setPageSize(50000);
        PageInfo<BillQueryRes> pageInfo = billService.queryPage(params);
        Asserts.isTrue(pageInfo.getTotal()<=50000,"最多支持导出50000条，请使用搜索条件减少导出数量！");
        if(pageInfo.getTotal()>0){
            final List<BillQueryExportRes> res = pageInfo.getList().parallelStream().map(o -> {
                final BillQueryExportRes billQueryExportRes = new BillQueryExportRes();
                billQueryExportRes.setOrderId(o.getOrderId());
                billQueryExportRes.setMerchant(o.getMerchantName()+"("+o.getMerchantCode()+")");
                billQueryExportRes.setCreatedDt(DateTimeUtil.formatter(o.getCreatedDt(), DateTimeUtil.bj_pattern));
                billQueryExportRes.setTotalAmount(AmountUtil.getYUAN(o.getTotalAmount()).toString());
                billQueryExportRes.setDiscount(AmountUtil.getYUAN(o.getDiscount()).toString());
                billQueryExportRes.setPayAmount(AmountUtil.getYUAN(o.getPayAmount()).toString());
                billQueryExportRes.setRefundTotalAmount(AmountUtil.getYUAN(o.getRefundTotalAmount()).toString());
                billQueryExportRes.setRefundDiscountAmount(AmountUtil.getYUAN(o.getRefundDiscountAmount()).toString());
                billQueryExportRes.setRefundAmount(AmountUtil.getYUAN(o.getRefundAmount()).toString());
                billQueryExportRes.setSettleStatus(AmountUtil.getYUAN(o.getSettleAmount()).toString());
                if (null != o.getPlatformPercent()) {
                    billQueryExportRes.setPlatformPercent(o.getPlatformPercent().toString() + "%");
                } else {
                    billQueryExportRes.setPlatformPercent("0");
                }
                billQueryExportRes.setPlatformAmount(AmountUtil.getYUAN(o.getPlatformAmount()).toString());
                billQueryExportRes.setMerchantAmount(AmountUtil.getYUAN(o.getMerchantAmount()).toString());
                billQueryExportRes.setSettleStatus(SettleStatusEnum.getDesc(o.getSettleStatus()));
                return billQueryExportRes;
            }).collect(Collectors.toList());
            String fileName = "账单列表导出.xlsx";
            Workbook workbook = ExcelUtil.buildWorkbook("账单列表", res);
            ExcelUtil.exportExcel(request, response, workbook, fileName);
        }
    }

    /**
     * 商户交易统计
     * @param platformMerchantId
     * @return
     */
    @RequestMapping(value = "/statistics", method = RequestMethod.GET)
    @ResponseBody
    public Result<TradeStatisticsRes> tradeStatistics(@RequestParam(name = "platformMerchantId",required = false) Long platformMerchantId) {
        TradeStatisticsRes result = billService.tradeStatistics(platformMerchantId);
        return Result.success(result);
    }



}
